<template>
  <el-card class="page-container">
    <template #header>
      <div class="header" style="display: flex">
        <div class="title">{{ title }}</div>
      </div>
    </template>
    <el-row>
      <el-col>
        <el-form
          ref="dishFormRef"
          class="form-inline"
          label-width="120px"
          :model="dishForm"
          :rules="rules"
          :inline="true"
        >
          <div style="display: flex">
            <el-form-item label="菜品名称:" prop="name">
              <el-input v-model="dishForm.name" placeholder="请填写菜品名称" />
            </el-form-item>
            <el-form-item label="菜品分类:" prop="categoryName">
              <el-select v-model="dishForm.categoryId" size="large" placeholder="请选择菜品分类">
                <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="菜品价格:" prop="price">
              <el-input v-model="dishForm.price" placeholder="请设置菜品价格" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="口味选择:">
              <el-form-item>
                <div class="flavorBox">
                  <el-button v-if="dishFlavors.length == 0" @click="addFlavore" type="primary"> 选择口味 </el-button>
                  <div v-else class="flavor">
                    <div class="cont">
                      <div v-for="(item, index) in dishFlavors" :key="index" class="items">
                        <div class="itTit">
                          <SelectInput
                            :leftDishFlavors="leftDishFlavors"
                            :index="index"
                            :value="item.name"
                            @select="selectHandle"
                          />
                        </div>
                        <div class="labItems" style="display: flex">
                          <span v-for="(it, ind) in item.value" :key="ind"
                            >{{ it }} <i @click="delFlavorLabel(index, ind)">X</i></span
                          >
                          <div class="inputBox" style="flex: 1 1 0%" />
                        </div>
                        <span class="delFlavor" @click="delFlavor(item.name)">删除</span>
                      </div>
                    </div>
                    <el-button
                      v-if="!!leftDishFlavors.length && dishFlavors.length < dishFlavorsData.length"
                      type="primary"
                      @click="addFlavore"
                      >添加口味</el-button
                    >
                  </div>
                </div>
              </el-form-item>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="菜品图片:" prop="image">
              <ImgUpload :image="imageUrl" @onImageChange="onImageChange"></ImgUpload>
            </el-form-item>
          </div>
          <el-form-item label="菜品描述:" prop="description">
            <el-input
              v-model="dishForm.description"
              :rows="3"
              maxlength="100"
              autosize
              style="width: 350px"
              placeholder="菜品描述,最多100字"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
          <div class="submit">
            <el-form-item>
              <el-button @click="router.back()">取消</el-button>
              <el-button type="primary" @click="saveHandle"> 保存 </el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import SelectInput from './components/SelectInput.vue'
import ImgUpload from '@/components/ImgUpload/index.vue'
import { ref, onMounted, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
// 菜品id
const dishId = route.query.id as number | null
const title = ref('')
const imageUrl = ref('')
// 菜品表单
const dishForm = ref({} as DishWithFlavorsResult)
// 菜品分类列表
import useCategory from '@/hooks/useCategory'
const { categoryList, getCategorysByType } = useCategory()
import { ElForm, ElMessage, FormRules } from 'element-plus'
import { addDishAPI, getDishAPI, putDishAPI } from '@/api/business/dish'
import { priceValidator } from '@/utils/validator'
import { CATEGORY_TYPE } from '@/constants'
import { DishWithFlavorsResult } from '@/types/dish'

const getDish = async () => {
  try {
    if (dishId != null) {
      title.value = '修改菜品'
      let { data } = await getDishAPI(dishId)
      dishForm.value = { ...data }
      imageUrl.value = data.image
      dishFlavors.value =
        data.flavors &&
        data.flavors.map(obj => ({
          ...obj,
          value: JSON.parse(obj.value),
        }))
      getLeftDishFlavors()
    } else {
      title.value = '添加菜品'
    }
  } catch (error) {
    console.log(error)
  }
}
onMounted(async () => {
  await Promise.all([getDish(), getCategorysByType(CATEGORY_TYPE.dish)])
})
// 菜品表单实例
const dishFormRef = ref<InstanceType<typeof ElForm> | null>(null)
// 校验规则
const rules = reactive<FormRules<typeof dishForm>>({
  name: [
    {
      required: true,
      validator: (_rule: any, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入菜品名称'))
        } else {
          const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
          if (!reg.test(value)) {
            callback(new Error('菜品名称输入不符,请输入2-20个字符'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur',
    },
  ],
  categoryId: [{ required: true, message: '请选择菜品分类', trigger: 'change' }],
  image: {
    required: true,
    message: '菜品图片不能为空',
  },
  price: {
    required: true,
    validator: priceValidator,
    trigger: 'blur',
  },
})

// 原始口味数据
const dishFlavorsData = [
  { name: '甜味', value: ['无糖', '少糖', '半糖', '多糖', '全糖'] },
  { name: '温度', value: ['热饮', '常温', '去冰', '少冰', '多冰'] },
  { name: '忌口', value: ['不要葱', '不要蒜', '不要香菜', '不要辣'] },
  { name: '辣度', value: ['不辣', '微辣', '中辣', '重辣'] },
]
//下拉框剩余可选择的口味数据
const leftDishFlavors = ref<typeof dishFlavorsData>([])
//已选择的口味的数据
const dishFlavors = ref<typeof dishFlavorsData>([])

//过滤已选择的口味下拉框无法再次选择
const getLeftDishFlavors = () => {
  const selectedNames = new Set(dishFlavors.value.map((item: any) => item.name))
  leftDishFlavors.value = dishFlavorsData.filter(item => !selectedNames.has(item.name))
  // console.log(leftDishFlavors.value)
}
// 选择并更新dishFlavors数组
const selectHandle = (val: string, key: number) => {
  const index = dishFlavorsData.findIndex(item => item.name === val)
  if (index !== -1) {
    const newArrDate = [...dishFlavors.value]
    newArrDate[key] = JSON.parse(JSON.stringify(dishFlavorsData[index]))
    dishFlavors.value = newArrDate
  }
}
// 添加口味
const addFlavore = () => {
  dishFlavors.value.push({ name: '', value: [] })
  // console.log(dishFlavors.value);
}
// 按钮 - 删除口味标签
const delFlavorLabel = (index: number, ind: number) => {
  dishFlavors.value[index].value.splice(ind, 1)
}
// 删除口味
const delFlavor = (name: string) => {
  const index = dishFlavors.value.findIndex((item: { name: string }) => item.name === name)
  dishFlavors.value.splice(index, 1)
  // console.log(dishFlavors.value);
}
// 监听dishFlavors的变化
watch(
  dishFlavors,
  (_newVal, _oldVal) => {
    getLeftDishFlavors()
    // console.log(dishFlavors.value);
  },
  { deep: true },
)
const onImageChange = (value: string) => {
  imageUrl.value = value
  dishForm.value.image = value
}

// 添加菜品/修改菜品
const saveHandle = () => {
  dishFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // if (!dishForm.value.image) {
      //   ElMessage.warning("菜品图片不能为空");
      // }
      let params = { ...dishForm.value }
      params.image = imageUrl.value
      params.flavors = dishFlavors.value.map((item: { name: string; value: string[] }) => ({
        ...item,
        value: JSON.stringify(item.value),
      }))
      if (title.value === '添加菜品') {
        await addDishAPI(params)
        ElMessage.success('添加成功')
        router.back()
      } else {
        await putDishAPI(params)
        ElMessage.success('修改成功')
        router.back()
      }
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>
<style scoped lang="scss">
.page-container{
  overflow: auto;
}
.flavorBox {
  width: 777px;

  .addBut {
    background: #ffc200;
    display: inline-block;
    padding: 0px 20px;
    border-radius: 3px;
    line-height: 40px;
    cursor: pointer;
    border-radius: 4px;
    color: #333333;
    font-weight: 500;
  }

  .flavor {
    border: solid 1px #dfe2e8;
    border-radius: 3px;
    padding: 15px;
    background: #fafafb;

    .cont {
      .items {
        display: flex;
        margin: 10px 0;

        .itTit {
          width: 150px;
          margin-right: 15px;

          input {
            width: 100%;
            // line-height: 40px;
            // border-radius: 3px;
            // padding: 0 10px;
          }
        }

        .labItems {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          border-radius: 3px;
          min-height: 39px;
          border: solid 1px #d8dde3;
          background: #fff;
          padding: 0 5px;

          span {
            display: inline-block;
            color: #ffc200;
            margin: 5px;
            line-height: 26px;
            padding: 0 10px;
            background: #fffbf0;
            border: 1px solid #fbe396;
            border-radius: 4px;
            font-size: 12px;

            i {
              cursor: pointer;
              font-style: normal;
            }
          }

          .inputBox {
            display: inline-block;
            width: 100%;
            height: 36px;
            line-height: 36px;
            overflow: hidden;
          }
        }

        .delFlavor {
          display: inline-block;
          padding: 0 10px;
          color: #f15959;
          cursor: pointer;
        }
      }
    }
  }
}
.submit {
  display: flex;
  justify-content: space-around;
}
</style>
